const recorderManager = wx.getRecorderManager();
import util from '../../../utils/util.js';
var app = getApp();
const FN = require('../../../utils/public');
import commonAPI from '../../../api/api'
const config = require('../../../utils/config');

const qiniuUploader = require("../../../utils/qiniuUploader");
const voice = wx.createInnerAudioContext();
const voice2 = wx.createInnerAudioContext();
var sto, correctSort = 1;
Page({

  /**
   * 页面的初始数据 
   */
  //mixins: [require('../../../mixin/themeChanged')],
  data: {
    priTmplIdArr: [],
    currWordArr: [],
    currWordIndex: 0,
    hasrecording: false,
    cutdownTime: 60,
    bgcolor: 'FB5844',
    options: {},
    vrObj: {},
    teaInfoObj: {},
    correctList: [],
    isPlaying: false,
    hasIntegralBtn: false,
    hasIntegral: false,
    hasSub: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setTeaInfo();
    wx.hideShareMenu(); // 禁止分享
    if (options.hasOwnProperty("freeCorrectMode")) {
      that.setData({
        hasIntegralBtn: true
      })
    }
    that.setData({
      options: options
    })
    that.initData();
    this.getSubscribeMsg();
    this.initQiniu(); // 初始化七牛
  },

  hasIntegralStatus: function (e) {
    this.setData({
      hasIntegral: e.detail.value
    })
  },

  //  
  initData: function () {
    var that = this;
    commonAPI.getVoiceByVrId({ vrId: that.data.options.vrId}).then(res => {
      if (res.code == '200') {
        var vr = res.data.length > 0 ? res.data[0] : null;
      if (vr != null) {
        vr.voiceResultInfo = JSON.parse(vr.voiceResultInfo);
        var temarr = [],
          wordsArr = [];
        if (vr.voiceResultInfo.result.words.length == 0) {
          var arr = temarr = vr.voiceToen.split(' ');
          for (var i = 0; i < arr.length; i++) {
            var o = {
              word: arr[i],
              pron_accuracy: 0
            }
            wordsArr.push(o);
          }
          vr.hasRepeatWord = 0;
          vr.voiceResultInfo.result.words = wordsArr;
        } else {
          vr.voiceResultInfo.result.words.map(function (item, i, arr) {
            temarr.push(item.word);
          });
        }
        vr.voiceResultAccuracy = isNaN(vr.voiceResultAccuracy) == true ? 0 : vr.voiceResultAccuracy;
        temarr.unshift("整句");
        temarr.unshift("语调");
        temarr.unshift("连读");
        temarr.unshift("发音技巧");
        that.setData({
          currWordArr: temarr
        })
      }
      that.setData({
        vrObj: vr
      })
      }
    })
  },

  // 播放声音
  playVoice: function (e) {
    var voiceurl = e.currentTarget.dataset.voiceurl, that = this;
    voice.stop();
    voice.src = voiceurl;
    voice.play();
    voice.onPlay(function () {
      FN.Loading(true, '播放中···')
    });

    voice.onStop(function () {
      FN.LoadingOff();
    });

    // 音频结束回调
    voice.onEnded(function () {
      FN.LoadingOff();
    });

    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr, // 收到预约申请通知,奖励领取通知
      success(res) {
        console.log('授权成功！');
      }
    })
  },

  // 播放原音 originalvoiceurl
  playOriginalVoice: function (e) {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr, // 收到预约申请通知,奖励领取通知
      success(res) {
        console.log('授权成功！');
      }
    })
    var voiceurl = e.currentTarget.dataset.originalvoiceurl;
    voice.stop();
    voice.src = voiceurl;
    voice.play();
    voice.onPlay(function () {
      FN.Loading(true, '原音播放中···')
    });

    voice.onStop(function () {
      FN.LoadingOff();
    });

    // 音频结束回调
    voice.onEnded(function () {
      FN.LoadingOff();
    });
  },

  // 删除
  delCorrectVoice: function (e) {
    var i = e.currentTarget.dataset.index,
      that = this;
    that.data.correctList.splice(i, 1);
    that.setData({
      correctList: that.data.correctList
    })
  },

  // 奖金领取通知
  bonusReceive: function () {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr, // 奖励领取通知
      success(res) {
        console.log('已授权接收订阅消息');
      }
    })
  },

  // 询问是否提交
  subdata: function () {
    var that = this;
    that.bonusReceive();
    wx.showModal({
      title: '提示',
      content: '是否提交',
      success(res) {
        if (res.confirm) {
          if (!that.data.hasSub) {
            that.setData({
              hasSub: true
            })
            that.saveCorrect();
          } else {
            FN.Toast('已提交')
          }
          wx.navigateBack({
            delta: 1
          })
        }
      }
    })
  },

  setTeaInfo: function () {
    var that = this;
    that.setData({
      teaInfoObj: app.globalData.userInfo.userObj,
    })
  },

  // 保存数据
  saveCorrect: function () {
    var that = this;
    if (that.data.correctList.length == 0) {
      FN.Toast('请先上传纠音')
      return;
    }
    var hci = '';
    if (that.data.hasIntegral) {
      hci = that.data.vrObj.hasOwnProperty('beforehandAppointmentStatus') == true ? '1' : '0'
    } else {
      hci = '-1';
    }
    commonAPI.teapushmsg4Stu({
      correctListJson: JSON.stringify(that.data.correctList),
      page:'pages/repeat/repeat?correctRecordBatch='+that.data.vrObj.voiceResultId,
        vsId: that.data.vrObj.voiceSystemId,
        voiceResultId: that.data.vrObj.voiceResultId,
        wdTeacherId: app.globalData.userInfo.userObj.wdTeacherId,
        wdTeacherName: app.globalData.userInfo.userObj.wdTeacherName,
        receiverOpenId: that.data.vrObj.openId,
        voiceToen: that.data.vrObj.voiceToen,
        baid: that.data.options.hasOwnProperty('baid') == true ? that.data.options.baid : null,
        hasConsumeIntegral: hci,
        "wxOpenInfo.wxOpenInfoSource": that.data.vrObj.wxOpenInfoSource
    }).then(res => {
      if (res.code == '200') {
        console.log(res);
      if (res.data.errcode == "0") {
        FN.Toast('纠音成功，消息已送达')
      } else {
        if (res.data.errcode != "0") {
          FN.Toast('纠音成功，但消息未送到,原因：' + res.msg)
        }
      }
      wx.navigateBack({
        delta: 1
      })
      FN.LoadingOff();
      }
    })
  },

  // 纠音选项
  bindPicker3Change: function (e) {
    this.setData({
      currWordIndex: e.detail.value
    })
  },

  // 试听老师的发音
  listenVoice: function (e) {
    var voiceurl = e.currentTarget.dataset.correctvoiceurl;
    voice2.stop();
    voice2.src = voiceurl;
    voice2.play();
    voice2.onPlay(function (res) {
      console.log(res);
      FN.Loading(true, '播放中···')
    });

    voice2.onStop(function () {
      FN.LoadingOff();
    });

    // 音频结束回调
    voice2.onEnded(function () {
      FN.LoadingOff();
    });
  },

  // 倒计时
  cutdownTime: function () {
    var time = 59,
      that = this;
    sto = setInterval(function () {
      if (time < 0) {
        clearInterval(sto);
        that.stopRecording();
      } else {
        that.setData({
          cutdownTime: time--
        })
      }
    }, 1000)
  },

  // 红点闪烁
  redRight: function () {
    var that = this;
    var sto = setInterval(function () {
      if (that.data.bgcolor == 'ffffff') {
        that.setData({
          bgcolor: 'FB5844'
        })
      } else {
        that.setData({
          bgcolor: 'ffffff'
        })
      }
    }, 800)
  },

  // 开始录音
  recording: function () {
    var that = this;
    const options = {
      duration: 60000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      wx.showLoading({
        title: '录音中···'
      })
      console.log('recorder start')
      that.setData({
        hasrecording: true
      })
      that.cutdownTime();
      that.redRight();
    });
    //错误回调
    recorderManager.onError((res) => {
      // that.stopRecording();
    })
  },

  // 暂停录音
  stopRecording: function () {
    var that = this;
    FN.LoadingOff();
    recorderManager.stop();
    this.setData({
      hasrecording: false
    })
    clearInterval(sto);

    recorderManager.onStop((res) => {
      this.setData({
        hasrecording: false
      })
      clearInterval(sto);
      that.subVoiceInfo(res);
    })
  },

  initQiniu: function () {
    var options = {
      region: 'ECN',
      uptokenURL: config.configApp.api_base_url+'qiniu/getUploadToken',
      domain: config.configApp.api_base_url,
      shouldUseQiniuFileName: true
    }
    // 将七牛云相关配置初始化进本sdk
    qiniuUploader.init(options);
  },

  // 上传到七牛云服务器
  subVoiceInfo: function (teacherCorrect) {
    var that = this, filePath = teacherCorrect.tempFilePath, fileName = 'studentRepeatVoice_'+new Date().getTime() + ".mp3";
    // 向七牛云上传
    qiniuUploader.upload(filePath, (res) => {
      res.fileName = fileName;
      if (res.hasOwnProperty("error")) {
        FN.Toast('上传失败，请重新录制')
      } else {
        var obj = {},
          tmparr = [];
        obj.word = that.data.currWordArr[that.data.currWordIndex];
        obj.correctVoiceUrl = res.fileURL;
        obj.voiceSystemId = that.data.vrObj.voiceSystemId;
        obj.avatarurl = app.globalData.userInfo.userObj.avatarUrl// 老师头像，用于在audio自定义组件显示老师头像。
        obj.wdTeacherName = app.globalData.userInfo.userObj.wdTeacherName// 老师头像，用于在audio自定义组件显示老师头像。
        // obj.timeduration = timeduration;
        obj.correctType = 3;
        obj.correctSort = ++correctSort;
        tmparr = that.data.correctList;
        tmparr.push(obj);
        that.setData({
          correctList: tmparr
        })
      }
    }, (error) => {
      console.error('error: ' + error);
    }, null, (progress) => {

    }, cancelTask => {

    }
    );
  },

  // 获取订阅消息
  getSubscribeMsg: function () {
    var that = this;
    commonAPI.getSubscribeMsg({ pageUrl: util.getCurrentPageUrl() }).then(res => {
      if (res.code == '200' && res.data.length > 0) {
        var arr = res.data[0].priTmplIdArr.split(",")
        that.setData({
          priTmplIdArr: arr
        })
      }
    })
  },

  audioClick: function (e) {
    var url = e.currentTarget.dataset.url;
    var obj = {
      useWebAudioImplement: false
    };
    var iac = wx.createInnerAudioContext(obj);
    iac.src = url;
    iac.onPlay(function () {
      FN.Loading(true, '播放中···')
    })
    iac.onEnded(function () {
      FN.LoadingOff();
    })
    this.setData({
      isPlaying: !this.data.isPlaying
    })
    if (this.data.isPlaying) {
      iac.play();
    } else {
      iac.pause();
    }
  }
})